<template>
  <searchInput :tableArray="valList" @inputChange="searChange" />
  <div class="down-bth">
    <el-button v-if="userRole == '1'" type="info" icon="UploadFilled" @click="downSome" style="margin-right: 20px;">导出文件</el-button>
    <countryFile v-if="userLevel=='国家级'||userRole == '1'" @editChange="fileChange" :reportItem="reportItem" :showEidt="showEidt" />
    <muban class="downMu" :templateType="form.templateType" />
  </div>
  <div class="table-box">
    <el-table 
      style="width: 90%;margin: 10px auto" 
      :data="tableData" 
      border 
      @selection-change="handleSelectionChange"
      :tooltip-options="{
           enterable: true, placement: 'right', showArrow: true, hideAfter: 200, popperOptions: { strategy: 'fixed' }
      }"
      :header-cell-style="{
      background: '#E7F2FF',
      color: 'black',
    }" v-loading="loading" :row-class-name="tableRowClassName">
      <el-table-column v-if="userRole == '1'" type="selection" width="55" :selectable="selectable" />
      <el-table-column prop="val" label="期别" width="150"  align="center" />
      <el-table-column label="报表状态" width="100"       align="center">
        <template #default="scope" v-if="userRole!='3'">
          {{ typeForm[scope.row.rState == '2'&& scope.row.checkInfoList[0].shState == 2?'5':scope.row.rState] }}
        </template>
        <template #default="scope" v-else>
          {{ typeForm[scope.row.rState] }}
        </template>
      </el-table-column>
      <el-table-column label="是否超时" width="100" align="center">
        <template #default="scope">
          {{ scope.row.notice ? '已超时' : '未超时' }}
        </template>
      </el-table-column>
      <el-table-column prop="deadline" label="填报/审核截至时间" width="180" align="center"/>
      <el-table-column prop="developArea" label="填报人" width="220" align="center" show-overflow-tooltip/>
      <el-table-column prop="checkTime" label="审核时间" width="180" align="center" />
      <el-table-column prop="reportTime" label="上报时间" width="180" align="center"/> 
      <el-table-column label="操作" min-width="240" width="auto" fixed="right" align="center">
        <template #default="scope">
           <!-- 省级 -->
          <div v-if="userRole == '1'&&scope.row.countryLevel!='1'">
          <el-button link type="primary" size="small"  @click="getCheck(scope.row,'first')">查看</el-button>
          <el-button link type="primary" size="small" @click="setTime(scope.row)" v-if="scope.row.rState == '1'">设置截止时间</el-button>
          <el-button link type="primary" size="small" @click="returnReport(scope.row, '1')"
            v-if="scope.row.rState == '2'&& scope.row.checkInfoList[0].shState != 2">通过</el-button>
          <el-button link type="primary" size="small" @click="returnReport(scope.row, '2')" style="color: red;"
            v-if="scope.row.rState != '1'">退回</el-button>
          <el-button link type="primary" size="small" @click="downReport(scope.row)"
            v-if="scope.row.rState != '1'">导出</el-button>
          </div>
           <!-- 市级 -->
          <div v-if="userRole == '2'&&scope.row.countryLevel!='1'">
          <el-button link type="primary" size="small"
            @click="getCheck(scope.row,'first')">查看</el-button>
          <el-button link type="primary" size="small" @click="returnReport(scope.row, '1')"
            v-if="scope.row.rState == '2'&& scope.row.checkInfoList[0].shState != 2">通过</el-button>
          <el-button link type="primary" size="small" @click="returnReport(scope.row, '2')" style="color: red;"
            v-if="scope.row.rState != '1' && scope.row.checkInfoList[0].shState != '2'">退回</el-button>
          <el-button link type="primary" size="small" @click="downReport(scope.row)"
            v-if="scope.row.rState != '1'">导出</el-button>
            <el-button link type="primary" size="small" @click="getCheck(scope.row,'second')">文件上传</el-button> 
          </div>
          <!-- 区级 -->
          <div v-if="userRole == '3'&&scope.row.countryLevel!='1'">
            <el-button link type="primary" size="small" v-if="scope.row.rState != '1'"
            @click="getCheck(scope.row,'first')">查看</el-button>
          <el-button link type="primary" size="small" @click="getEdit(scope.row,'first')"
            v-if="scope.row.rState == '1'">{{scope.row.tstate == '2'?'编辑':'填报'}}</el-button>
          <el-button link type="primary" size="small" @click="getReport(scope.row)"
            v-if="scope.row.rState == '1' && scope.row.tstate == '2'">上报</el-button>
          <el-button link type="primary" size="small" @click="downReport(scope.row)">导出</el-button>
          <el-button v-if="scope.row.rState == '1'" link type="primary" size="small" @click="getEdit(scope.row,'second')">文件上传</el-button>
          </div>
          <!-- 国家级 -->
          <div v-if="userRole != '2'&&scope.row.countryLevel=='1'">
            <!-- <el-button link type="primary" size="small" @click="returnReport(scope.row, '2')" style="color: red;"
              v-if="scope.row.rState != '1' && userRole != '3'">退回</el-button> -->
            <el-button v-if="scope.row.rState!='1'" link type="primary" size="small" @click="downCountry(scope.row)">国家级导出</el-button>
            <el-button v-if="userRole != '1'" link type="primary" size="small" @click="editCountry(scope.row)">报表修改</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination :total="totals" layout="prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" v-model:current-page="form.currentPage" v-model::page-size="form.pageNum" />
    </div>
  </div>
  <digflow :flowlist="showData" :show="showFlow" @digChange="flowChange" />
  <!-- 设置时间的弹窗 -->
  <el-dialog v-model="showSetbox" title="设置截至时间" width="30%" :before-close="handleClose" style="text-align: center;">
    <div>
      <el-date-picker v-model="deadline" type="datetime" placeholder="请设置开始提醒时间" format="YYYY-MM-DD hh:mm:ss"
        value-format="YYYY-MM-DD hh:mm:ss" />
    </div>
    <div style="padding-left: 70px;margin-top: 30px;">
      <el-select v-model="noticeDay" class="m-2" placeholder="请选择天数">
        <el-option v-for="item in 10" :key="item" :label="item" :value="item" />
      </el-select>
      前几天提醒
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showSetbox = false">取消</el-button>
        <el-button type="primary" @click="sureTime">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 上报成功展示 -->
  <div class="showBox" v-if="showSuccess">
    <img src="../../assets/images/Check-Circle-Fill.png" alt="">
    <span>上报成功</span>
  </div>
  <el-dialog v-model="returnShow" title="退回" width="30%">
    <span>原因：</span><el-input v-model="returnInfo.reason" autocomplete="off" style="width: 300px" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="returnShow = false">取消</el-button>
        <el-button type="primary" @click="sureReturn">
          退回
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import searchInput from '@/components/searchInput.vue';
import muban from '@/components/muban.vue';
import countryFile from '@/components/countryFile.vue';
import { findListS, reportFindList, reportFindById, reportSave, reportExport, reportpublish, reportcheck, getAllval,downAll } from "@/util/api";
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
//流程组件
import digflow from '../../components/flowDig.vue'
const userRole = ref(JSON.parse(sessionStorage.getItem('userInfo')).userRole)
const userLevel = ref(JSON.parse(sessionStorage.getItem('userInfo')).level)
const router = useRouter()
//等待
const loading: any = ref(false)
//流程数据
const showData: any = ref([])
//展示流程管理
const showFlow: any = ref(false)
//设置截至的对象
const setItem: any = ref({})
//展示设置窗口
const showSetbox: any = ref(false)
//退回窗口
const returnShow: any = ref(false)
//设置时间
const deadline: any = ref('')
//设置提醒天数
const noticeDay: any = ref()
//上报成功
const showSuccess: any = ref(false)
//勾选的报表
const multipleSelection :any = ref([])
//修改报表id
const reportItem:any =ref({}) 
//展示修改
const showEidt:any=ref(false)
//报表请求参数
const form: any = ref({
  checkUserId: '',
  createUserId: '',
  developArea: '',
  rState: '',
  reportTimeEnd: '',
  reportTimeStart: '',
  state: '1',
  templateType: '',
  val: '',
  currentPage: 1, //第几页
  pageNum: 10, //一页几个
})
//报表状态
const typeForm: any = ref({
  '1': '未上报',
  '2': '未审批',
  '4': '已退回',
  '5': '已审批' 
})
//退回和通过参数
const returnInfo: any = ref({
  id: '',
  shResult: '',
  reason: ''
})
//总条数   
const totals: any = ref(0)
//报表数据     
const tableData: any = ref([])
//期别列表
const valList: any = ref([])
//获取报表
const getTable = async () => {
  loading.value = true
  if (userRole.value == '3') { //区级 
    var res: any = await reportFindList(form.value);
  } else {  //省市
    var res: any = await findListS(form.value);
  }
  // console.log(res);
  if (res.code == 200) {
    tableData.value = []
    tableData.value = res.data.content;
    totals.value = parseInt(res.data.totalElements);
    loading.value = false
    getVal()
  }
};
//获取期别列表
const getVal = async () => {
  const res: any = await getAllval(form.value.templateType)
  //  console.log(res)
  if (res.code != 200) return
  valList.value = res.data
}
//分页
const handleSizeChange = (val: number) => {
  form.value.pageNum = val;
  getTable();
};
const handleCurrentChange = (val: number) => {
  form.value.currentPage = val;
  getTable();
};
//关闭弹窗
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭弹窗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

//流程管理
const getFlow = (item: any) => {
  reportFindById(item.id).then((res: any) => {
    showData.value = res.data.checkInfoList
    showFlow.value = true
  })
};
//关闭流程管理
const flowChange = (e: any): void => {
  // console.log(e)
  showFlow.value = e
}
//编辑
const getEdit = (item: any,tabs:any) => {
  console.log(item)
  let url = null
  if(item.templateId=='5'){
    url= router.resolve({
    path: '/dominantCheck',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
    })
  }else if(item.templateId=='4'){
    url= router.resolve({
    path: '/fourCheck',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else if(item.templateId=='100'){
    url= router.resolve({
    path: '/summary',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else if(item.templateId=='101'){
    url= router.resolve({
    path: '/staging',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else if(item.templateId=='102'){
    url= router.resolve({
    path: '/poor',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }else{
    url= router.resolve({
    path: '/check',
    query: {
      id: item.id,
      radio1: item.templateId,
      tabs:tabs
    }
  })
  }
  window.open(url.href);
} 
//报表查看
const getCheck = (val: any,tabs:any) => {
  let url = null
  if(val.templateId=='5'){
    url= router.resolve({
    path: '/dominantCheck',
    query: {
      id: val.id,
      radio1: val.templateId,
      tabs:tabs,
      isCheck:1
    }
    })
  }else if(val.templateId=='4'){
    url=  router.resolve({
    path: '/fourCheck',
    query: {
      id: val.id,
      radio1: val.templateId,
      tabs:tabs,
      isCheck:1
    }
  })}else if(val.templateId=='100'){
    url=  router.resolve({
    path: '/summary',
    query: {
      id: val.id,
      radio1: val.templateId,
      tabs:tabs,
      isCheck:1
    }
  })}else if(val.templateId=='101'){
    url=  router.resolve({
    path: '/staging',
    query: {
      id: val.id,
      radio1: val.templateId,
      tabs:tabs,
      isCheck:1
    }
  })}else if(val.templateId=='102'){
    url=  router.resolve({
    path: '/poor',
    query: {
      id: val.id,
      radio1: val.templateId,
      tabs:tabs,
      isCheck:1
    }
  })}else{
    url=  router.resolve({
    path: '/check',
    query: {
      id: val.id,
      radio1: val.templateId,
      tabs:tabs,
      isCheck:1
    }
  })
  }
  // console.log(val)
  window.open(url.href);
}
//设置截至时间
const setTime = (item: any) => {
  setItem.value = item;
  showSetbox.value = true
}
//确定设置
const sureTime = async () => {
  if (deadline.value == '' || noticeDay.value == '') return ElMessage.error('请填入时间')
  setItem.value['deadline'] = deadline.value
  setItem.value['noticeDay'] = noticeDay.value
  setItem.value['setDeadline'] = true
  let res: any = await reportSave(setItem.value)
  if (res.code != 200) return
  ElMessage.success('设置成功')
  showSetbox.value = false
  getTable()

}
//上报
const getReport = async (item: any) => {
  if(item.filesQ==null&&item.filesS==null)return ElMessage.error('请先上传文件')
  let res: any = await reportpublish(item.id)
  if (res) {
    showSuccess.value = true
    getTable();
    setTimeout(() => {
      showSuccess.value = false
    }, 1500);
  }
}
//退回和通过
const returnReport = (val: any, type: any) => {
  returnInfo.value.reason = ""
  returnInfo.value.id = val.checkInfoList[0].id
  returnInfo.value.shResult = type
  if (type == '1') { //通过
    ElMessageBox.confirm(
      '确定通过?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      let res: any = await reportcheck(returnInfo.value)
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: '通过成功',
        })
        getTable()
      }
    })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消通过',
        })
      })
  } else {//退回
    returnShow.value = true
  }
}
//确认退回
const sureReturn = () => {
  reportcheck(returnInfo.value).then((res: any) => {
    if (!res) return
    ElMessage({
          type: 'success',
          message: '已退回',
        })
    returnShow.value = false
    getTable()
  })
}
//导出
const downReport = (val: any) => {
  // console.log(val.id)
  let name = val.name
  reportExport(val.id).then((res: any) => {
    console.log(res)
    let fileName = name + ".xlsx"
    handleFileError(res, fileName)
  })
}
//选择报表
const handleSelectionChange=(val:any)=>{
  multipleSelection.value=val
  // console.log(val)
}
//批量导出
const downSome = async ()=>{
   let downArray=[]
   if(multipleSelection.value.length<=0)return  ElMessage({
          type: 'info',
          message: '请勾选',
   })
   multipleSelection.value.forEach((element:any) => {
    downArray.push(element.id)
   });
  //  console.log(downArray)
   let res:any = await downAll(downArray)
  //  console.log(res)
   let time = new Date().toLocaleDateString()
   handleFileError(res,time+'文件.zip')
}
const handleFileError = (res: any, fileName: any) => {
  if (typeof res.data !== 'undefined') {
    if (res.data.type === 'application/json') {
      const reader = new FileReader();
      reader.onload = function () {
      };
      reader.readAsText(new Blob([res.data]));
    }
  } else {
    var downloadUrl = window.URL.createObjectURL(new Blob([res]));
    var a = document.createElement('a');
    a.style.display = 'none';
    a.href = downloadUrl;
    a.download = fileName;
    var event = new MouseEvent('click');
    a.dispatchEvent(event);
  }
};

//国家级报表导出
const downCountry=(item:any)=>{
  if(item.file==null)return ElMessage.error('无报表')
  let  flieitem = JSON.parse(item.file)[0]
  // console.log(flieitem)
  let link = document.createElement('a')
    link.style.display = 'none';
    link.href = '/api/file/show/'+flieitem.saveName;
    link.download = flieitem.showName;
    link.click()
    window.URL.revokeObjectURL(link.href)
}
//国家级报表修改
const editCountry=(e:any)=>{
  console.log(1)
  reportItem.value = e
  showEidt.value=true
 }

const fileChange =(isFrash:Boolean)=>{
  showEidt.value=false
  reportItem.value={}
  if(isFrash){
    getTable()
  }
  
 }
onMounted(() => {
  form.value.templateType = router.currentRoute.value.meta.query
  getTable()
})
//动态添加table背景
const tableRowClassName = ({
  row,
  rowIndex,
}) => {
  if (row.notice) {
    return 'warning-row'
  }
}
//动态禁用选择
const selectable = (row:any,index:number)=>{
     if(row.rState=='1')return false
     return true
}
//inputChange搜索框
const searChange = (e: any): void => {
  //  console.log(e)
  form.value.rState = e.rState//状态
  form.value.val = e.val//期别
  form.value.reportTimeEnd = e.reportTimeEnd//结束时间
  form.value.reportTimeStart = e.reportTimeStart//开始时间
  //重置页数
  form.value.currentPage = 1
  getTable()
}
//获取请求报表类型参数
watch(
  () => router,
  (newValue: any) => {
    form.value.templateType = newValue.currentRoute.value.meta.query
    form.value.rState = ''//状态
    form.value.val = ''//期别
    form.value.reportTimeEnd = ''//结束时间
    form.value.reportTimeStart = ''//开始时间
    form.value.currentPage=1
    form.value.pageNum=10
    getTable()
  },
  { deep: true }
)
</script>
<style lang="scss">
.el-table .warning-row {
  --el-table-tr-bg-color: rgba(235, 76, 64, 0.1);
}
</style>
<style lang="scss" scoped>
.pagination-box {
  width: 90%;
  margin: 30px auto;

  ::v-deep(.el-pagination) {
    float: right;
  }
}

.showBox {
  width: 326px;
  height: 208px;
  position: fixed;
  background-color: white;
  box-shadow: 0px 3px 29px 10px #D9D9D9;
  left: calc(50% - 163px);
  top: calc(50% - 104px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: 500;
  z-index: 9999;

  img {
    display: block;
    width: 70px;
    height: 70px;
  }
}
.down-bth{
  width: 90%;
  display: flex;
  margin: 20px auto;
}
.downMu{
  margin-left: 20px;
}
</style>

